package com.damai.action.json.impl;

import java.util.Map;
import java.util.Map.Entry;
import java.util.TreeMap;

import com.citywithincity.api.utils.ApiUtil;
import com.citywithincity.utils.MD5Util;
import com.damai.utils.LogUtil;

public class SignUtil {

	/**
	 * 准备数据
	 * @param map	数据
	 * @param mchId	商户号
	 * @param key	秘钥
	 * @return
	 */
	public static TreeMap<String, Object> prepareData(TreeMap<String, Object> map,String mchId,String key){
		map.put("mch_id", mchId);
		map.put("rand_str", MD5Util.md5Appkey(String.valueOf(System.nanoTime() * Math.random())));
		map.put("time", System.currentTimeMillis()/ 1000);
		String sign = getSign(map, key);
		map.put("sign", MD5Util.md5Appkey(sign));
		return map;
	}
	
	/**
	 * 对返回结果进行验证
	 * @param data
	 * @return
	 */
	public static boolean validate(Map<String, Object> json,String key){
		String sign = (String)json.get(ApiUtil.sign);
		if(sign==null){
			return false;
		}
		json.remove("sign");
		if(!json.containsKey(ApiUtil.rand_str)){
			return false;
		}
		if(!json.containsKey(ApiUtil.time)){
			//判断时间(略)
			return false;
		}
		
		String newSign = SignUtil.getSign(new TreeMap<String, Object>(json),key);
		String countSing =  MD5Util.md5Appkey(newSign);
		if(sign.equals(countSing)){
			return true;
		}
		
		LogUtil.log("待加密数据:%s 计算签名：%s 上送签名:%s", newSign, countSing, sign);
		
		return false;
	}
	
 	private static String getSign(TreeMap<String, Object> data,String key) {
		//先移除sign字段
		data.remove("sign");
		
		StringBuilder sb = new StringBuilder();
		boolean first = true;
		for (Entry<String, Object> entry : data.entrySet()) {
			if(first){
				first = false;
			}else{
				sb.append("|");
			}
			sb.append(entry.getKey()).append("=").append(entry.getValue());
		}
		sb.append(key);
		
		
		return sb.toString();
	}
}
